package com.meiqiang.chat.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;
import java.net.URL;

/*
 1.SimpleChannelInboundHandler 是ChannelInboundHandlerAdapter的子类
 2.HttpObject 客户端和服务器端相互通讯的数据被封装成HttpObject
 */
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    /**
     * 监听读取客户端数据
     * @param ctx
     * @param httpObject
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject httpObject) throws Exception {
        if (httpObject instanceof HttpRequest){
            System.out.println("msg 类型="+httpObject.getClass());
            System.out.println("客户端地址："+ctx.channel().remoteAddress());

            HttpRequest httpRequest = (HttpRequest)httpObject;
            //获取url
            URI uri = new URI(httpRequest.uri());
            if (uri.getPath().equals("/favicon.ico")){
                System.out.println("请求了 /favicon.ico 不做相应");
                return;
            }

            //回复消息给浏览器 http 协议
            ByteBuf buf = Unpooled.copiedBuffer("hello,我是服务器", CharsetUtil.UTF_8);

            //构建一个http相应
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=utf-8");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,buf.readableBytes());
            //将构建好的response返回
            ctx.writeAndFlush(response);
        }
    }
}
